// src-electron/main.js
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const {
  app,
  BrowserWindow,
  Menu,
  ipcMain,
  Tray,
  globalShortcut,
} = require("electron");
const { join } = require("path");
const fs = require("fs");
const __dirname = import.meta.dirname;

// 声明托盘应用
let tray = null;
// 声明主应用窗口
let win = null;
// 声明设置窗口
let settingsWin = null;
// 声明预加载脚本配置
const commonWebPreferences = {
  contextIsolation: true,
  preload: join(__dirname, "./preload.js"),
};

// 屏蔽安全警告
// ectron Security Warning (Insecure Content-Security-Policy)
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";

// 创建浏览器窗口时，调用这个函数。
const createWindow = () => {
  if (win) return;
  // 创建应用窗口
  win = new BrowserWindow({
    width: 600,
    height: 240,
    title: "Salary",
    frame: false, // 去掉默认的窗口边框，包括标题栏（应用名称，缩小放大，关闭按钮）
    resizable: false, // 禁止调整窗口大小
    maximizable: false,
    icon: join(__dirname, "../src/assets/images/logo/orange.png"),
    webPreferences: commonWebPreferences,
  });

  // 关闭默认菜单栏
  Menu.setApplicationMenu(null);

  // 禁用右键菜单
  if (process.platform === "win32") {
    win.hookWindowMessage(278, (e) => {
      win.setEnabled(false);
      setTimeout(() => {
        win.setEnabled(true);
      }, 100);
      return true;
    });
  }
  // win.loadURL('http://localhost:3000')
  // development模式
  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(process.env.VITE_DEV_SERVER_URL);
    // 开启调试台
    win.webContents.openDevTools();
  } else {
    win.loadFile(join(__dirname, "../dist/index.html"));
  }
};

const createSettingsWindow = () => {
  if (settingsWin) {
    settingsWin.focus();
    return;
  }

  settingsWin = new BrowserWindow({
    width: 420,
    height: 580,
    title: "设置",
    resizable: false,
    minimizable: true,
    maximizable: false,
    icon: join(__dirname, "../src/assets/images/logo/orange.png"),
    webPreferences: commonWebPreferences,
  });

  // 加载设置页面
  if (process.env.VITE_DEV_SERVER_URL) {
    settingsWin.loadURL(`${process.env.VITE_DEV_SERVER_URL}#/settings`);
  } else {
    settingsWin.loadFile(join(__dirname, "../dist/index.html"), {
      hash: "settings",
    });
  }

  settingsWin.once("ready-to-show", () => {
    settingsWin.show();
  });

  settingsWin.on("closed", () => {
    settingsWin = null;
  });
};

// Electron 会在初始化后并准备
app.whenReady().then(() => {
  createWindow();
  // 托盘图标与菜单
  createTray();
  // 创建快捷键方便打开控制台
  globalShortcut.register("Control+I", () => {
    if (BrowserWindow.getFocusedWindow()) {
      BrowserWindow.getFocusedWindow().webContents.openDevTools();
    }
  });
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
      createTray();
    }
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});

// 创建托盘图标
function createTray() {
  if (tray) return; // 防止重复创建

  tray = new Tray(join(__dirname, "../src/assets/images/logo/orange.png"));

  const contextMenu = Menu.buildFromTemplate([
    {
      label: "显示窗口",
      click: () => {
        win.show();
        win.setSkipTaskbar(false);
      },
    },
    {
      label: "设置",
      click: () => {
        if (settingsWin) {
          settingsWin.show();
          settingsWin.focus();
        } else {
          createSettingsWindow();
        }
      },
    },
    {
      label: "退出应用",
      click: () => {
        tray.destroy();
        tray = null;
        win.destroy();
        win = null;
        app.quit();
      },
    },
  ]);

  tray.setToolTip("Salary 工具");
  tray.setContextMenu(contextMenu);

  // 点击图标也可以恢复窗口
  tray.on("click", () => {
    win.show();
    win.setSkipTaskbar(false);
  });
}

// 监听渲染进程发送过来的消息
// 主窗口隐藏至托盘
ipcMain.on("window-close", () => {
  // 隐藏程序窗口
  win.hide();
  // 隐藏任务栏图标
  win.setSkipTaskbar(true);
});

// 关闭设置窗口
ipcMain.on("setting-close", () => {
  settingsWin.hide();
});

// handle与invoke是另一种收发消息的方式，invoke发送后会得到handle返回的promise结果， 而send和on这种方式中，send不会有返回结果
// 保存软件配置 event是electron内置参数，e为传入的配置阐述
ipcMain.handle("save-config", (event, params) => {
  const e = JSON.parse(params);
  console.log('params',e)
  // 1.获取原有配置文件
  const data = fs.readFileSync(join(__dirname, "./config.json"), "utf-8");
  const config = JSON.parse(data);
  // 2.合并原有配置文件和传入的配置文件
  if (e.workTime) config.workTime = e.workTime;
  if (e.offWorkTime) config.offWorkTime = e.offWorkTime;
  if (e.salary) config.salary = e.salary;
  if (e.salaryDate) config.salaryDate = e.salaryDate;
  config.holidayMode = e.holidayMode;
  if (e.themeColor) config.themeColor = e.themeColor;
  if (e.picture && typeof e.picture === "string") config.picture = e.picture;
  fs.writeFileSync(join(__dirname, "./config.json"), JSON.stringify(config));
    // 重载主窗口页面
  if (win) {
    win.reload();
  }
});

// 读取软件配置
ipcMain.handle("load-config", () => {
  const data = fs.readFileSync(join(__dirname, "./config.json"), "utf-8");
  return JSON.parse(data);
});

// 重置软件配置
ipcMain.handle("reset-config", () => {
  const data = fs.readFileSync(join(__dirname, "./config.json"), "utf-8");
  const config = JSON.parse(data);
  Object.assign(config, config.default)
  fs.writeFileSync(join(__dirname, "./config.json"), JSON.stringify(config));
    // 重载主窗口页面
  if (win) {
    win.reload();
  }
})
